package com.zaoqi.controller;

import com.zaoqi.pojo.Result;
import com.zaoqi.service.AliOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/files", produces = "application/json;charset=UTF-8")
public class FileController {

    @Autowired
    private AliOssService aliOssService;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            String objectName = "uploads/" + file.getOriginalFilename();
            String fileUrl = aliOssService.upload(bytes, objectName);
            Map<String, Object> data = new HashMap<>();
            data.put("fileUrl", fileUrl);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/download")
    public Result downloadFile(@RequestParam("objectName") String objectName) {
        try {
            String fileContent = aliOssService.download(objectName);
            Map<String, Object> data = new HashMap<>();
            data.put("fileContent", fileContent);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("文件下载失败: " + e.getMessage());
        }
    }
}
